package com.zheng.security.handles;

import cn.hutool.json.JSONUtil;
import com.zheng.security.utils.ApiResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当没有权限时返回自定义JSON
 * @author zyq
 * @Description
 * @createTime 2021年01月15日 20:45:00
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSONUtil.parse(ApiResponse.error(403, "暂无权限", "暂无权限")));
        response.getWriter().flush();
    }
}
